<?php

class DefaultController extends Controller
{
	public $layout = 'awt-resource';
	public function actionIndex()
	{
		$path = YiiBase::getPathOfAlias('webroot.res.mp3s');
		$rs = scandir($path);
		$ids = array();
		foreach ($rs as $name) {
			if ($name[0]==='a') {
				
				$count = 0;
				$id = substr($name,1);
				
				$rs2 = scandir(YiiBase::getPathOfAlias('webroot.res.mp3s.a'.$id));
				foreach ($rs2 as $name2)
					if ($name2[0]==='b')
						$count++;
				
				$ids[] = array(
					'id'=>$id,
					'count'=>$count,
				);
			}
		}
		$result = Yii::app()->db->createCommand()
			->select('*')
			->from('artist a')
			->queryAll();
		$newResult = array();
		foreach ($result as $key => $row) {
			$newResult[$row['id']] = $row;
		}
		$this->render('list_artist',array(
			'ids'=>$ids,
			'result'=>$newResult,
		));

	}
	
	public function actionListAlbum($aid) {
		$aid = intval($aid);
		$rs = scandir(YiiBase::getPathOfAlias('webroot.res.mp3s.a'.$aid));
		$ids = array();
		foreach ($rs as $name) {
			if ($name[0]==='b') {
				$ids[] = substr($name,1);
			}
		}
		$result = Yii::app()->db->createCommand()
			->select('*')
			->from('album a')
			->where('artist_id=:id', array(':id'=>$aid))
			->queryAll();
		$newResult = array();
		foreach ($result as $key => $row) {
			$newResult[$row['id']] = $row;
		}
		$this->render('list_album',array(
			'ids'=>$ids,
			'result'=>$newResult,
			'aid'=>$aid,
		));
	}
	
	public function actionListSong($aid,$bid) {
		$aid = intval($aid);
		$bid = intval($bid);
		$rs = scandir(YiiBase::getPathOfAlias('webroot.res.mp3s.a'.$aid.'.b'.$bid));
		$ids = array();
		foreach ($rs as $name) {
			if (substr($name,-4)==='.mp3') {
				$ids[] = substr($name,0,-4);
			}
		}
		sort($ids,SORT_NUMERIC);
		$result = Yii::app()->db->createCommand()
			->select('*')
			->from('song a')
			->where('album_id=:id', array(':id'=>$bid))
			->queryAll();
		$newResult = array();
		foreach ($result as $key => $row) {
			$newResult[$row['track_no']] = $row;
		}
		$this->render('list_song',array(
			'result'=>$newResult,
			'ids'=>$ids,
			'aid'=>$aid,
			'bid'=>$bid,
		));
	}
	
	public function actionGetSong($aid,$bid,$tid) {
		$aid = intval($aid);
		$bid = intval($bid);
		$path = YiiBase::getPathOfAlias('webroot.res.mp3s.a'.$aid.'.b'.$bid).DIRECTORY_SEPARATOR.$tid.'.mp3';
		
		$filename = $path;
		$handle = fopen($filename, "r");
		$contents = fread($handle, filesize($filename));
		fclose($handle);
		
		header('Content-Type: audio/mpeg');
		echo $contents;
	}
}